package com.dfbz.netctoss.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class SpringCacheConfig {

    //默认是jdk类型序列化方式
    @Bean("redisTemplate")
    public RedisTemplate<Object, Object> getRedisTemplate(RedisConnectionFactory factory){
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

        //设置key-value的序列化方式
        redisTemplate.setKeySerializer(stringRedisSerializer);//默认utf-8对key编码和解码
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);

        //设置hash类型的序列化方式
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        return redisTemplate;
    }

    //设置缓存管理器
    @Bean
    public RedisCacheManager getRedisCacheManager(RedisTemplate<Object, Object> redisTemplate){
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig().serializeKeysWith
                (RedisSerializationContext.
                        SerializationPair.
                        fromSerializer(redisTemplate.getStringSerializer())).serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate
                        .getValueSerializer())).entryTtl(Duration.ofMinutes(10));
        RedisCacheManager cacheManager =
                RedisCacheManager.RedisCacheManagerBuilder.
                        fromConnectionFactory(redisTemplate.getConnectionFactory())
                        .cacheDefaults(configuration).build();
        return cacheManager;

    }
}
